package com.base.servlet.core;

import com.base.servlet.http.HttpServlet;
import com.base.servlet.http.HttpServletRequest;
import com.base.servlet.http.HttpServletResponse;
import com.base.servlet.http.HttpServletResponseWrapper;
import com.base.servlet.message.HttpConvert;
import com.base.servlet.message.HttpMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: Jeffrey
 * @date: 2022/01/23/10:07
 * @description: 前端控制器，核心逻辑组装Handler
 */
@ChannelHandler.Sharable
@Slf4j
public class DispatcherServlet extends ChannelInboundHandlerAdapter {

    private static HandlerMapping handlerMapping ;

    /*加载HandlerMapping*/
    public DispatcherServlet() {
        /*1.加载XML映射*/
        handlerMapping = new HandlerMapping();
    }

    /**
     *
     * @param ctx Channel上下文
     * @param msg HttpMessage
     * @throws Exception e
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        /*2.创建HttpConvert*/
        HttpConvert convert = new HttpConvert(ctx.channel());
        /*3.将读到Msg转换成HttpServletRequest*/
        HttpServletRequest request = convert.convertToRequest((HttpMessage) msg);
        log.debug("request=="+request);
        /*4.创建HttpServletResponse对象*/
        HttpServletResponse httpServletResponse = new HttpServletResponseWrapper();
        /*5.根据request 获取映射*/
        String url = request.getRequestUrl();
        String[] split = url.split("\\?");
        String urlMapping = split[0];
        Class<HttpServlet> handlerClass = handlerMapping.getHandlerClass(urlMapping);
        /*6.执行handler*/
        HttpServlet httpServlet = handlerClass.getConstructor().newInstance();
        httpServlet.init(request,httpServletResponse);
        HttpMessage fromResponse = convert.convertFromResponse((HttpServletResponseWrapper) httpServletResponse);
        ctx.writeAndFlush(fromResponse);
    }
}
